/*
 * @author: jackem.mojx@gmail.com
 */
package com.ansion.utils;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.net.ConnectivityManager;
import android.os.Build;
import android.text.TextUtils;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.ansion.log.VLog;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.List;


public class ApplicationHelper implements NetBroadCastReceiver.NetworkStateListener {

    private static float density = 180;
    private static Context mContext;
    private static int width;
    private static int height;

    private static String strMarketType = "";
    private static String strLocalversion = "";
    private static boolean backgroundStat = false;


    private static int versionCode;
    private static String strUserAgent;
    private static boolean isHighDisplay = true;
    private static ApplicationHelper s_ins = null;
    private static int commType;

    private final static int ScreenType_480_850 = 0;
    private final static int ScreenType_480_800 = 1;
    private final static int ScreenType_455_320 = 2;
    private static NetBroadCastReceiver receiver = null;

    public static Context getContext() {
        if (mContext == null) {
            mContext = ResourceUtils.getContext();
        }
        return mContext;
    }


    public static void setUserAgent(String userAgent) {
        strUserAgent = userAgent;
        strUserAgent = strUserAgent.trim();
        strUserAgent = strUserAgent.replace("\r", "");
        strUserAgent = strUserAgent.replace("\n", "");
    }

    public static String getUserAgent() {
        if (TextUtils.isEmpty(strUserAgent)) {
            StringBuilder builder = new StringBuilder();
            builder.append("(").append(getContext().getPackageName()).append("_").append(getStrLocalversion()).append(")(")
                    .append("Android;").append(Build.DEVICE).append(";")
                    .append(Build.VERSION.RELEASE).append(")(")
                    .append(getEncodeTTID()).append(")");
            strUserAgent = builder.toString().trim();
            strUserAgent = strUserAgent.replace("\r", "");
            strUserAgent = strUserAgent.replace("\n", "");
        }
        return strUserAgent;
    }

    private static String getEncodeTTID() {
        try {
            return URLEncoder.encode(getTTID(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }


    public static float getDensity() {
        return density;
    }

    public static int getScreenWidth() {
        return width;
    }

    public static int getScreenHeight() {
        return height;
    }

    public static int getScreenSizeType() {

        final int screenWidth = getScreenWidth();
        final int screenHeight = getScreenHeight();
        if (screenWidth >= 480 && screenHeight >= 850) {
            return ScreenType_480_850;
        }
        if (screenWidth == 480 && screenHeight == 800) {
            return ScreenType_480_800;
        }
        if (screenWidth <= 480 && screenHeight <= 320) {
            return ScreenType_455_320;
        }
        return ScreenType_480_850;
    }

    public static boolean isHighDisplay() {
        return isHighDisplay;
    }

    public static String getTTID() {
        if (TextUtils.isEmpty(strMarketType) && getContext() != null) {
            InputStream is = null;
            BufferedReader br = null;
            try {
                AssetManager am = getContext().getAssets();
                is = am.open("sourceid.dat");
                br = new BufferedReader(new InputStreamReader(is));
                strMarketType = br.readLine().trim();
            } catch (Throwable e) {
                strMarketType = "play";
            } finally {
                try {
                    if (br != null)
                        br.close();
                    if (is != null)
                        is.close();
                } catch (Throwable e) {
                    VLog.eonly(e);
                }
            }
        }
        return strMarketType;
    }


    //initEnv is called within Application.onCreate
    ApplicationHelper() {

    }

    public static ApplicationHelper getInstance() {
        if (null == s_ins) {
            s_ins = new ApplicationHelper();
        }
        return s_ins;
    }

    public static void initEnv(Context context) {
        String trackKey = "APP_START";
        VLog.stopD(trackKey, "%s initEnv inner start", trackKey);
        mContext = context;
        //ZusNotificationCenter.defaultCenter().init(mContext); //use LocalBroadcastManager instead
        density = mContext.getResources().getDisplayMetrics().density;
        VLog.stopD(trackKey, "%s initEnv inner 1", trackKey);
        width = mContext.getResources().getDisplayMetrics().widthPixels;
        VLog.stopD(trackKey, "%s initEnv inner 2", trackKey);
        height = mContext.getResources().getDisplayMetrics().heightPixels;
        VLog.stopD(trackKey, "%s initEnv inner 3", trackKey);

        strUserAgent = getUserAgent();
        if (width >= 480 && height >= 800) {
            isHighDisplay = true;
        } else {
            isHighDisplay = false;
        }
        VLog.stopD(trackKey, "%s initEnv inner 4", trackKey);
        receiver = new NetBroadCastReceiver(ApplicationHelper.getInstance());
        commType = receiver.searchCommuType(mContext);
        //System Broadcast
        mContext.registerReceiver(receiver, new IntentFilter(
                ConnectivityManager.CONNECTIVITY_ACTION));

    }


    /**
     * Checks if the application is in the background (i.e behind another application's Activity).
     *
     * @return true if another application is above this one.
     */
    public static boolean isRunningForeground() {
        if (getContext() == null) return false;
        ActivityManager am = (ActivityManager) getContext().getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(getContext().getPackageName())) {
                return true;
            }
        }

        return false;
    }


    public static void setBackgroundState(boolean btrue) {
        backgroundStat = btrue;
    }

    public static boolean getBackgroundState() {
        return backgroundStat;
    }

    @Override
    public void commuTypeChange(int type) {
        commType = type;
        Intent intent = new Intent(AZusIntentConstant.ACTION_NETWORK_CHANGE);
        intent.putExtra("nettype", commType);
        LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
    }


    public static String getStrLocalversion() {//lazyLoad版本名
        if (!TextUtils.isEmpty(strLocalversion))
            return strLocalversion;
        try {
            strLocalversion = getContext().getPackageManager().getPackageInfo(
                    getContext().getPackageName(), 0).versionName;
        } catch (NameNotFoundException e) {
            VLog.eonly(e);
        }
        return strLocalversion;
    }

    public static int getVersionCode() {//lazyLoad版本号
        if (versionCode == 0) {
            try {
                versionCode = getContext().getPackageManager().getPackageInfo(getContext().getPackageName(), 0).versionCode;
            } catch (NameNotFoundException e) {

            }
        }
        return versionCode;
    }

    public static String getStrUserAgent() {
        return strUserAgent;
    }

    public static void setStrUserAgent(String strUserAgent) {
        ApplicationHelper.strUserAgent = strUserAgent;
    }


}
